<template>
   <view>
   	<view class="dataBackground">
   		<picker mode="date" :value="todate" @change="bindDateChange" class="sports_time">
   		    <text style="font-size: 24px">{{ todate }}</text>
   		</picker>
   	</view>
       <view :class="firstBackground">
           <view class="firstAddCard" v-for="(item, index) in sportsCards" :key="item.id">
               <text class="cardContent">{{ item.sportsName }}</text>
			   
			   <text class="cardContent">{{ item.sportsKJ }}卡路里</text>
   
               <text class="cardContent">{{ item.sportsTime }}分钟</text>
   
               <view class="deleteButton" @tap="deleteCard(index)">删除</view>
           </view>
           <view :class="add" @tap="addSportsCards">
               <image class="addCardsImg" src="https://s4.ax1x.com/2022/02/05/HmHyp8.png"></image>
           </view>
       </view>
       <textarea cols="30" rows="10" class="text" placeholder="说点什么吧" @blur="inputContent"></textarea>
       <view :class="dynamicLength">
           <view v-for="(item, index) in photos" :key="item.id">
               <image :src="item.photoSrc" class="photoBackground"></image>
           </view>
           <view :class="canAdd">
               <image src="https://s4.ax1x.com/2022/02/05/HnWnDP.png" class="photoImg" @tap="photo"></image>
           </view>
       </view>
       <view class="jurisdictionBackground">
           <image class="jurisdictionImg" src="https://s4.ax1x.com/2022/03/03/bYS9zD.png"></image>
           <text class="jurisdictionText" style="left: 17rpx; top: -17rpx">谁可以看</text>
           <text class="jurisdictionText" style="left: 286rpx; top: -16rpx" @tap="setJurisdiction">{{ who }}</text>
           <image class="jurisdictionSetImg" @tap="setJurisdiction" src="https://s4.ax1x.com/2022/02/06/HKDeBD.png"></image>
       </view>
       <view class="issueBackground">
           <button @tap="issue" class="issueButton">发布</button>
       </view>
   </view>
</template>
<script>
// pages/health/food/clockIn/clockIn.js
const date = new Date();
export default {
	globalData:
	{
		list2: [],
		sportsKJ:0,
		sportsId:0,
		sportsTime:0,
		sportsName:"",
	},
    data() {
        return {
            todate:
                date.getFullYear() +
                '-' +
                (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) +
                '-' +
                (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()),
			who: '公开',
			cardSum: 0,
			add: 'firstAddCard',
			photos: [],
			sportsCards: [],
			photosNum: 0,
			dynamicLength: 'dynamicLength0',
			firstBackground: 'firstBackground0',
			canAdd: 'photoBackground',
			date: '',
			content:'',
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
		this.who=options.id
		var num=getApp().globalData.sportsNum
		var name=getApp().globalData.sportsName
		var time=getApp().globalData.sportsTime
		var id=getApp().globalData.sportsId
		if(num!=-1 && num!=undefined){
			this.sportsCards=getApp().globalData.list2
			if(this.sportsCards==undefined)
				this.sportsCards=[]
			this.sportsCards.push({id: this.sportsCards.length+1,sportsKJ:0,sportsName:name,sportsId:id,sportsTime:time})
			getApp().globalData.list2=this.sportsCards
			getApp().globalData.sportsNum=-1
			if(this.sportsCards.length==9)
				this.add="hide"
			if(this.sportsCards.length>=3)
				this.firstBackground='firstBackground1'
			if(this.sportsCards.length>=6)
				this.firstBackground='firstBackground2'
		}
	},
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
		var num=getApp().globalData.sportsNum
		var name=getApp().globalData.sportsName
		var time=getApp().globalData.sportsTime
		var id=getApp().globalData.sportsId
		if(num!=-1 && num!=undefined){
			this.sportsCards=getApp().globalData.list2
			if(this.sportsCards==undefined)
				this.sportsCards=[]
			this.sportsCards.push({id: this.sportsCards.length+1,sportsKJ:0,sportsName:name,sportsId:id,sportsTime:time})
			getApp().globalData.list2=this.sportsCards
			getApp().globalData.sportsNum=-1
			if(this.sportsCards.length==9)
				this.add="hide"
			if(this.sportsCards.length>=3)
				this.firstBackground='firstBackground1'
			if(this.sportsCards.length>=6)
				this.firstBackground='firstBackground2'
		}
	},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        bindDateChange: function (e) {
            console.log(e.detail.value);
            this.setData({
                date: e.detail.value
            });
        },
        
        addSportsCards: function () {
            uni.navigateTo({
                url: '/pages/health/sports/search/search'
            });
        },
        
        setJurisdiction: function () {
            uni.navigateTo({
                url: '/pages/health/sports/clockIn/jurisdiction/jurisdiction'
            });
        },
        
        photo: function () {
            var that = this;
            uni.chooseImage({
                count: 9,
                success: function (res) {
                    var photo = that.photos;
                    var num = that.photos.length;
                    var str = that.dynamicLength;
                    var str1 = that.canAdd;
        
                    if (num == 8) {
                        str1 = 'hide';
                    }
        
                    if (num == 2) {
                        str = 'dynamicLength1';
                    }
        
                    if (num == 5) {
                        str = 'dynamicLength2';
                    }
        
                    photo.push({
                        id: 1,
                        photoSrc: res.tempFilePaths
                    });
                    that.setData({
                        photos: photo,
                        photosNum: num + 1,
                        dynamicLength: str,
                        canAdd: str1
                    });
                }
            });
        },
        
        issue: function () {
			var searchResult=[]
			var urlstr = 'exerciseInfo/get/id=' + this.sportsCards[0]['sportsId']
			var time=this.sportsCards[0]['sportsTime']
			this.$https({
				url: this.$baseUrl + urlstr,
				success: (res) => {
					if (res.statusCode == 200) {
							searchResult.push({
								'category': res.data['data'].category,
								'id': res.data['data'].id,
								'name': res.data['data'].name,
								'pic': res.data['data'].pic,
								'state': res.data['data'].state,
								'ratio': res.data['data'].ratio,
								'version': res.data['data'].version,
						})
					} else {
						uni.showToast({
							title: res.data.errorCode,
							icon: 'error',
						})
					}
				},
			
				fail: (e) => {
					console.log(e)
					uni.showToast({
						title: '搜索失败',
						icon: 'error',
					})
				}
			});
			uni.request({
				url:this.$baseUrl + 'clockIn/exercise',
				method:"POST",
				header:{
					"session":"shadow-test",
					'Accept': 'application/json',
					"Content-Type":"application/json",
				},
				data:{
						  "amount": time*searchResult['category'],
						  "content": this.content,
						  "exerciseInfoId": searchResult['id'],
						  "time": time
					},
				success:(res)=>{
					console.log(res)
					if(res.statusCode==200)
					{
						for(let index=1;index<=this.photos.length;index++)
						{
							uni.uploadFile({
								url:this.$baseUrl + 'clockIn/food/pic/id='+res.data['data']+'/sequence='+index,
								filePath:this.photos[index-1].photoSrc[0],
								name:'file',
								header:{
									"session":"shadow-test",
									'Accept': 'application/json',
									"Content-Type":"application/json",
								},
								success:(res)=>{
									console.log(res)
									if(res.statusCode==200)
									{
										console.log("ok")
									}
									else
									{
										uni.showToast({
										  title: res.data.errorCode,
										  icon: 'error',
										})
									}
								},
								fail:(e)=>{
									console.log(e)
									uni.showToast({
									  title: '发布失败',
									  icon: 'error',
									})
								}
							})
						}
					}
					else
					{
						uni.showToast({
						  title: res.data.errorCode,
						  icon: 'error',
						})
					}
				},
				fail:(e)=>{
					console.log(e)
					uni.showToast({
					  title: '发布失败',
					  icon: 'error',
					})
				}
			})
        },
		inputContent: function(e){
			this.content=e.detail.value
		},
		deleteCard: function(e){
			this.sportsCards.splice(e,1)
		}
    }
};
</script>
<style>
@import './clockIn.css';
</style>
